package com.mipo;

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;
import org.bson.types.ObjectId;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.QueryOperators;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;


public class MongoUtil2 {
	
	public static void main(String[] args) throws Exception {
		/*连接到MongoDB服务 如果是远程连接可以替换localhost为服务器所在IP地址
		两个参数分别服务器地和端口*/
		ServerAddress serverAddress = new ServerAddress("172.31.12.54", 22017);
		List<ServerAddress> addrs = new ArrayList<ServerAddress>();
		addrs.add(serverAddress);
		//三个参数分别用户名、数据库名、密码
		MongoCredential credential = MongoCredential.createMongoCRCredential("zsmongo", "third_swap_data", "zsmd@017".toCharArray());
		List<MongoCredential> credentials = new ArrayList<MongoCredential>();
		credentials.add(credential);
		//通过连接认证获取MongoDB连接
		MongoClient mongoClient = new MongoClient(addrs, credentials);
		MongoDatabase db = mongoClient.getDatabase("third_swap_data");
		MongoCollection<Document> users = db.getCollection("c006");
		
		//getFirst(users);
		//useCursor(users);
		operation(users);
		
		mongoClient.close();
		
	}
	
	/*取第一个*/
	public static void getFirst(MongoCollection<Document> users){
		FindIterable<Document> documents = users.find().skip(1).limit(1); // 从1开始取1条数据，下标从0开始
		System.out.println("queryAll:" + documents.first());
	}
    
	/*使用游标*/
    public static void useCursor(MongoCollection<Document> users){
    	MongoCursor<Document> cursor = users.find().iterator();
    	while(cursor.hasNext()) {
    		Document ducument = cursor.next();
    		System.out.println(ducument);
    	}
    }
    
    /*各种查询操作，文档如下：*/
    /*
	{
	    "_id" : "PD625265202660769792",
	    "productCode" : "PD625265202660769792",
	    "productName" : "防震自救安全常识",
	    "productType" : 2,
	    "createTime" : "2017-09-01 09:40:41",
	    "price" : 5.98,
	    "unit" : 0,
	    "ownerType" : "4",
	    "orgId" : "84344fc513224720aa211759c3f52c1a",
	    "orgName" : "唐浙江直属学校",
	    "userId" : "58c2f47ce3ff4043ae4e74f830be8d99",
	    "userName" : "信丽",
	    "userAccount" : "t_xinyanli03",
	    "detailUrl" : "http://res.t.zjle.cn/cms-portal/goResDetailInfo_Square.html?productCode=PD625265202660769792",
	    "isPrice" : "1",
	    "viewCount" : 29,
	    "downCount" : 28,
	    "collectedCount" : 1,
	    "commentCount" : 0,
	    "marks" : 0,
	    "fileId" : "70d68c584394451586b40521bf787173",
	    "fileName" : "防震自救安全常识",
	    "format" : "file",
	    "fileLength" : 20936095,
	    "downloadUrl" : "http://res.t.zjle.cn:20002/cms-ft/rest/product/download/PD625265202660769792",
	    "resIdList" : [ 
	        "44267910bb7a4c67ae764b7013daf65a"
	    ],
	    "periodIdList" : [ 
	        "cz"
	    ],
	    "periodNameList" : [],
	    "subjectIdList" : [ 
	        "jcsub02"
	    ],
	    "subjectNameList" : [],
	    "editionIdList" : [ 
	        "bb02"
	    ],
	    "editionNameList" : [],
	    "gradeIdList" : [ 
	        "11"
	    ],
	    "gradeNameList" : [],
	    "volumeIdList" : [ 
	        "V028"
	    ],
	    "volumeNameList" : [],
	    "textbookIdList" : [ 
	        "47569"
	    ],
	    "chapterIdList" : [ 
	        "47582"
	    ],
	    "thumbnailUrlList" : [ 
	        null
	    ],
	    "proStyle" : "qiTa",
	    "proGs" : "qiTa",
	    "fileSize" : "",
	    "from" : "studio",
	    "resForm" : "1",
	    "platformCodeList" : [ 
	        "330000"
	    ],
	    "req" : {
	        "curPage" : 7
	    },
	    "updateResInfo" : {
	        "begUnique" : 1271960003,
	        "pushMap" : {
	            "extension" : "file",
	            "filename" : "防震自救安全常识",
	            "filepath" : "http://res.t.zjle.cn:20002/cms-ft/rest/product/download/PD625265202660769792",
	            "fileurl" : "http://res.t.zjle.cn:20002/cms-ft/rest/product/download/PD625265202660769792",
	            "length" : 20936095,
	            "previewurl" : "http://res.t.zjle.cn/cms-portal/goResDetailInfo_Square.html?productCode=PD625265202660769792",
	            "thumburl" : "null",
	            "title" : "防震自救安全常识"
	        },
	        "result" : {
	            "resourceId" : "{\"code\":0,\"data\":{\"data\":\"d13e67ff41454fe59228dc1ffe195f4f\"}}"
	        }
	    }
	}
    */
    public static void operation(MongoCollection<Document> users){
    	/*查询_id = 4de73f7acd812d61b4626a77*/
    	FindIterable<Document> documents = null;
    	documents = users.find(new BasicDBObject("_id", "PD625264624958308352")); /*因为存的时候_id被存为字符串,所以第二个参数为字符串。如果是_id默认为ObjectId对象，则第二个参数应该为 new ObjectId("4de73f7acd812d61b4626a77")*/
    	System.out.println("1:" + documents.first());
    	
    	/*查询downCount = 28*/
    	documents = users.find(new BasicDBObject("downCount", 28));
    	System.out.println("2:" + documents.first());
    	
    	/*查询downCount >= 28*/
    	documents = users.find(new BasicDBObject("downCount", new BasicDBObject("$gte", 28)));
    	System.out.println("3:" + documents.first());
    	
    	/*查询downCount <= 28*/
    	documents = users.find(new BasicDBObject("downCount", new BasicDBObject("$lte", 28)));
    	System.out.println("4:" + documents.first());
    	
    	/*查询downCount != 28*/
    	documents = users.find(new BasicDBObject("downCount", new BasicDBObject("$ne", 28)));
    	System.out.println("5:" + documents.first());
    	
    	/*查询downCount in 25/26/27*/
    	documents = users.find(new BasicDBObject("downCount", new BasicDBObject(QueryOperators.IN, new int[]{25, 26, 27})));
    	System.out.println("6:" + documents.first());
    	
    	/*查询downCount not in 25/26/27*/
    	documents = users.find(new BasicDBObject("downCount", new BasicDBObject(QueryOperators.NIN, new int[]{25, 26, 27})));
    	System.out.println("7:" + documents.first());
    	
    	/*查询updateResInfo字段存在的记录*/
    	documents = users.find(new BasicDBObject("updateResInfo", new BasicDBObject(QueryOperators.EXISTS, true)));
    	System.out.println("8:" + documents.first());
    	
    	/*删除记录*/
    	DeleteResult result = users.deleteOne(new BasicDBObject("_id", "PD625264624958308352"));
    	System.out.println("9:" + result.getDeletedCount());
    	
    	/*模糊查询*/
    	
    	
    	
    	
    	/*增加记录*/
    	/*
		{
		    "_id" : ObjectId("5b20de76e19b0f0aac3895d7"),
		    "name" : "hoojo",
		    "age" : 50,
		    "sex" : "男",
		    "children" : {
		        "name" : "jack",
		        "age" : 25,
		        "sex" : "男",
		        "grandSon" : [ 
		            {
		                "name" : "jack",
		                "age" : 25,
		                "sex" : "男"
		            }, 
		            {
		                "name" : "jack",
		                "age" : 25,
		                "sex" : "男"
		            }
		        ]
		    }
		}
    	*/
    	Document grandSon = new Document();
        grandSon.put("name", "jack");
        grandSon.put("age", 25);
        grandSon.put("sex", "男");
        
        Document grandDaught = new Document();
        grandDaught.put("name", "jack");
        grandDaught.put("age", 25);
        grandDaught.put("sex", "男");
        
        ArrayList<Document> grands = new ArrayList<Document>();
        grands.add(grandSon);
        grands.add(grandDaught);
    	
        Document son = new Document();
        son.put("name", "jack");
        son.put("age", 25);
        son.put("sex", "男");
        son.put("grandSon", grands);
        
        Document user = new Document();
        user.put("name", "hoojo");
        user.put("age", 50);
        user.put("sex", "男");
        user.put("children", son);
        
        users.insertOne(user);
        
        users.updateOne(new BasicDBObject("_id", new ObjectId("5b20de76e19b0f0aac3895d7")), new BasicDBObject("age", 99));
    	
    	
    	
    }
    
    
    	
    	
    	

}


